//
//  HMStatusViewModel.swift
//  Weibo
//
//  Created by Apple on 2017/7/13.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
import YYText

//  处理微博数据显示逻辑
class HMStatusViewModel: NSObject {

    //  引用模型
    var status: HMStatus? {
        didSet {
            handleMbrankImage(mbrank: status?.user?.mbrank ?? 0)
            handleVerifiedTypeImage(verifiedType: status?.user?.verified_type ?? -1)
            if let currentStatus = status {
                handleRetweetContent(status: currentStatus)
                
            }
            handleSourceContent(source: status?.source ?? "")
            originalAttributedStr = handleAttributedStr(text: status?.text ?? "", isOriginal: true)
        }
    }
    
    //  会员等级图片
    var mbrankImage: UIImage?
    //  认证类型等级
    var verifiedTypeImage: UIImage?
    //  转发微博内容
    var retweetContent: String?
    //  来源内容
    var sourceContent: String?
    //  原创微博富文本
    var originalAttributedStr: NSAttributedString?
    //  转发微博富文本
    var retweetAttributeStr: NSAttributedString?
    
    //  处理微博富文本
    private func handleAttributedStr(text: String, isOriginal: Bool) -> NSAttributedString {
        //  微博内容转富文本
        let attributedStr = NSMutableAttributedString(string: text)
        //  使用正则匹配微博内容里面的表情描述
        let regular = try! NSRegularExpression(pattern: "\\[\\w+\\]", options: [])
        //  匹配表情描述
        let chsMatchResultArray = regular.matches(in: text, options: [], range: NSMakeRange(0, (text as NSString).length))
        var fontSize: CGFloat = 13
        var textColor: UIColor = UIColor.darkGray
        if isOriginal == false {
            fontSize = 12
            textColor = UIColor.lightGray
        }
        //  遍历匹配结果
        for chsMatchResult in chsMatchResultArray.reversed() {
            let chsRange = chsMatchResult.range
            let chs = (text as NSString).substring(with: chsRange)
            //  根据表情描述查找表情模型
            if let emoticon = HMEmoticonTools.sharedTools.searchEmoticonWith(chs: chs) {
                //  找到了表情模型，表情模型转富文本
//                let emoticonAttributeText = NSAttributedString.attributedStringWithEmoticon(emoticon: emoticon, font: UIFont.systemFont(ofSize: fontSize))
                let image = UIImage(named: emoticon.path!, in: emoticonBundle, compatibleWith: nil)!
                //  使用YYText提供创建富文本的方式
                let emoticonAttributeText = NSAttributedString.yy_attachmentString(withEmojiImage: image, fontSize: fontSize)!
                //  替换指定表情描述范围为表情富文本
                attributedStr.replaceCharacters(in: chsRange, with: emoticonAttributeText)
            }
        }
        
        //  统一设置富文本的字体大小
        attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: fontSize), NSForegroundColorAttributeName: textColor], range: NSMakeRange(0, attributedStr.length))
        
        //   添加高亮富文本颜色
        addHighlitedAttributedText(attributedStr: attributedStr, pattern: "@[^:：]+")
        addHighlitedAttributedText(attributedStr: attributedStr, pattern: "#[^#]+#")
        addHighlitedAttributedText(attributedStr: attributedStr, pattern: "http[s]?://[^\\s\\u4e00-\\u9fa5]+")
        
        
        return attributedStr
    }
    
    
    //  设置高亮富文本颜色
    func addHighlitedAttributedText(attributedStr: NSMutableAttributedString, pattern: String) {
        //  创建匹配高亮文字正则
        let highlightRegular = try! NSRegularExpression(pattern: pattern, options: [])
        //  匹配高亮文字范围
        let highlightedMatchResultArray = highlightRegular.matches(in: attributedStr.string, options: [], range: NSMakeRange(0, (attributedStr.string as NSString).length))
        for highlightedMatchResult in highlightedMatchResultArray {
            //  高亮文字范围
            let highlightedRange = highlightedMatchResult.range
            let color = UIColor(red: 80 / 255, green: 125 / 255, blue: 215 / 255, alpha: 1)
            //  设置高亮范围的富文本颜色
            attributedStr.addAttributes([NSForegroundColorAttributeName: color], range: highlightedRange)
            
            let textHighlight = YYTextHighlight()
            //  背景色
            let bgColor = UIColor(red: 177 / 255, green: 215 / 255, blue: 255 / 255, alpha: 1)
            let textBorder = YYTextBorder(fill: bgColor, cornerRadius: 3)
            //  设置边框的内间距
            textBorder.insets = UIEdgeInsets(top: 1, left: 0, bottom: 0, right: 0)
            textHighlight.setBackgroundBorder(textBorder)
            //  设置高亮背景色
            attributedStr.yy_setTextHighlight(textHighlight, range: highlightedRange)
            
        }
    }
    
    //  时间
    var timeContent: String? {
        guard let createAt = status?.created_at else {
            return nil
        }
        let dt = DateFormatter()
        //  判断是否是今年
        if isThisYear(createAt: createAt) {
            print("是今年")
            //  当前日历对象
            let calendar = Calendar.current
            //  判断是否是今天
            if calendar.isDateInToday(createAt) {
                //  今天
                let timeInterval = abs(createAt.timeIntervalSinceNow)
                if timeInterval < 60 {
                    return "刚刚"
                } else if timeInterval < 3600 {
                    let result = timeInterval / 60
                    return "\(Int(result))分钟前"
                } else {
                    let result = timeInterval / 3600
                    return "\(Int(result))小时前"
                }
                
                
            } else if calendar.isDateInYesterday(createAt) {
                //  昨天
                dt.dateFormat = "昨天 HH:mm"
            } else {
                //  其它
                dt.dateFormat = "MM-dd HH:mm"
            }
            
            
        } else {
            print("不是今年")
            dt.dateFormat = "yyyy-MM-dd HH:mm"
        }
        return dt.string(from: createAt)
    }
    
    private func isThisYear(createAt: Date) -> Bool {
        let dt = DateFormatter()
        dt.dateFormat = "yyyy"
        let createAtYear = dt.string(from: createAt)
        let currentYear = dt.string(from: Date())
        return createAtYear == currentYear
    }
    
    
    //  处理来源内容
    private func handleSourceContent(source: String) {
        if let startRange = source.range(of: "\">"), let endRange = source.range(of: "</") {
            //  指定范围内最大的光标位置索引
            let startIndex = startRange.upperBound
            //  指定范围内最小的光标位置索引
            let endIndex = endRange.lowerBound
            sourceContent = "来自: " + source.substring(with: startIndex..<endIndex)
        }
    }
    
    //  处理转发微博内容
    private func handleRetweetContent(status: HMStatus) {
        if let retweetStatus = status.retweeted_status {
            if let name = retweetStatus.user?.screen_name, let text = retweetStatus.text {
                retweetContent = "@\(name): \(text)"
                //  转发微博富文本
                retweetAttributeStr = handleAttributedStr(text: retweetContent!, isOriginal: false)
            }
        }
    }
    
    //  处理认证类型等级图片
    private func handleVerifiedTypeImage(verifiedType: Int) {
        switch verifiedType {
        case 0:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedTypeImage = nil
        }
    }
    
    //  处理会员等级图片
    private func handleMbrankImage(mbrank: Int) {
        if mbrank >= 1 && mbrank <= 6 {
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
    }
    
    
    
}
